from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.conf import settings
from django.core.paginator import *
from .models import *
import os

# Create your views here.
def index(request):
    return render(request,'booktest/index.html')

def myExcept(request):
    a = int('aaaaa')
    return HttpResponse('hello')

def upload(request):
    return render(request,'booktest/upload.html')

def uploadhandle(request):
    upfile = request.FILES.get('pic1')
    path = os.path.join(settings.MEDIAROOT,upfile.name)
    with open(path,'wb') as f:
        for info in upfile.chunks():
            f.write(info)

    str1 = '''
    <html>
    <img src='static/media/%s' width=220 height=300/>
    上传成功
    </html>
        '''%upfile.name
    return HttpResponse(str1)

def pageShow(request,pn):
    if pn == "":
        pn = '1'
    list = HeroInfo.objects.all()
    paginator = Paginator(list,4)
    page = paginator.page(int(pn))
    context = {'page':page}
    return render(request,'booktest/herolist.html',context)

def area(request):
    return render(request,'booktest/area.html')

def getArea1(request):
    list = AreaInfo.objects.filter(aParent_id=0)
    list2 = []
    for a in list:
        list2.append([a.id, a.atitle])
    return JsonResponse({'data': list2})

def getArea2(request, pid):
    list = AreaInfo.objects.filter(aParent_id=pid)
    list2 = []
    for a in list:
        list2.append({'id': a.id, 'title': a.atitle})
    return JsonResponse({'data': list2})